package com.acce.system.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;

import com.acce.base.config.BrowserType;
import com.acce.base.utils.PlatformUtils;
import com.acce.system.dao.IUserDao;
import com.acce.system.pojo.UserList;

/**
 * 
 * Servlet Filter implementation class AuthFilter
 * 
 * @author mahuang
 *
 */
@Service("authFilter")
@WebFilter(description = "权限验证", urlPatterns = { "/pages/*", "/index.html" })
public class AuthFilter implements Filter {
	
	private IUserDao userDao;
	
	private Logger logger = Logger.getLogger(AuthFilter.class);

    public AuthFilter() {
    }

	public void init(FilterConfig fConfig) throws ServletException {
		
		ServletContext sc = fConfig.getServletContext(); 
        XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null && cxt.getBean("IUserDao") != null && userDao == null) {
        	userDao = (IUserDao) cxt.getBean("IUserDao");
		}
	}

	public void destroy() {
	}

	/**
	 * 权限认证过滤
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		String userAgent = request.getHeader("User-agent");
		
		if(BrowserType.webcat.getValue() == PlatformUtils.checkPlatform(userAgent)) {
			logger.info("Handle Webcat ...");
			handleWebcat(request, response, chain);
		} else {
			logger.info("Handle PC ...");
			handlePC(request, response, chain);
		}
	}
	
	private void handleWebcat(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

		
		chain.doFilter(request, response);
	}
	
	private void handlePC(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		//获得请求的URL
		String url = request.getRequestURL().toString();

		//获得session中的对象

		HttpSession session= request.getSession();

		UserList sessuse = (UserList) session.getAttribute("sessuse");
		
		//如果session中不存在用户登录信息, 则从cookie中获取用户信息并
		if(sessuse == null) {
			Cookie[] cs = request.getCookies();
			
            if (cs != null && cs.length > 0) {
                for (Cookie c : cs) {
                    String cName = c.getName();
                    if (cName.equals("qwebuer")) {
                    	//query user id
                        String qwebuer = c.getValue();
                    	UserList ul = new UserList();
                    	ul.setAtUserId(qwebuer);
                    	sessuse = userDao.getUserById(ul);
                        request.getSession().setAttribute("sessuse", sessuse);
                    }
                }  
            }  
		}
		
		chain.doFilter(request, response);
	}

}
